/**
 * 
 */
package org.compiere.model;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;

import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;

/**
 * @author V.Sokolov
 *
 */
public class Mhrmidcard extends X_hrm_idcard {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -7631822209361260500L;
	
	/**	Static Logger	*/
	private static CLogger	s_log	= CLogger.getCLogger (Mhrmidcard.class);

	/**
	 * @param ctx
	 */
	public Mhrmidcard(Properties ctx) {
		super(ctx);
	}

	/**
	 * @param ctx
	 * @param hrm_idcard_ID
	 * @param trxName
	 */
	public Mhrmidcard(Properties ctx, int hrm_idcard_ID, String trxName) {
		super(ctx, hrm_idcard_ID, trxName);
	}

	/**
	 * @param ctx
	 * @param rs
	 * @param trxName
	 */
	public Mhrmidcard(Properties ctx, ResultSet rs, String trxName) {
		super(ctx, rs, trxName);
	}

	/** Load Model for BPartner */
    public static Mhrmidcard getHRM_Card (int C_BPartner_ID, String type, boolean isActive)
    {
    	if(C_BPartner_ID == 0 || type.isEmpty() || type == null)
    		return null;
    	String active = "Y";
    	if(!isActive)
    		active = "N";
    	
    	Mhrmidcard empcard = new Mhrmidcard(Env.getCtx(), 0, null);
    	PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		// Employee data from the card
				String sql_ = "SELECT * FROM hrm_idcard WHERE hrm_idcard.C_BPARTNER_ID=? \n"+
						"AND hrm_idcard.AD_CLIENT_ID=? \n" +
						"AND hrm_idcard.hrm_docType='"+type+"' \n"+
						"AND hrm_idcard.STARTDATE = (SELECT MAX(H.STARTDATE) FROM hrm_idcard H WHERE H.C_BPARTNER_ID=hrm_idcard.C_BPARTNER_ID \n " +
													 "AND H.hrm_docType='"+type+"') \n"+
						"AND hrm_idcard.ISACTIVE='" + active + "'";
		try
		{
			pstmt = DB.prepareStatement(sql_,null);
			pstmt.setInt(1, C_BPartner_ID);
			pstmt.setInt(2, Env.getAD_Client_ID(Env.getCtx()));
			rs = pstmt.executeQuery();
			if(rs.next())
				empcard = new Mhrmidcard(Env.getCtx(), rs, null);			
		}
		catch (SQLException e)
		{
			s_log.log(Level.SEVERE, "product", e);
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}
		return empcard;	
    }

}
